package com.weiquan.controller;

import com.weiquan.common.Result;
import com.weiquan.service.SmsService;
import com.weiquan.service.impl.SmsServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/sms")
@Tag(name = "短信服务", description = "短信验证码发送和验证相关接口")
@Validated
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private SmsServiceImpl smsServiceImpl;

    /**
     * 发送注册验证码
     */
    @PostMapping("/send/register")
    @Operation(summary = "发送注册验证码", description = "向指定手机号发送注册验证码")
    public Result<Map<String, Object>> sendRegisterCode(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            HttpServletRequest request) {
        
        String clientIp = getClientIp(request);
        log.info("发送注册验证码请求，手机号：{}，IP：{}", phoneNumber, clientIp);
        
        boolean success = smsService.sendRegisterCode(phoneNumber);
        
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "验证码发送成功");
            result.put("expireTime", 5 * 60); // 5分钟有效期
            result.put("remainingTime", smsServiceImpl.getSendLimitTime(phoneNumber));
            
            return Result.success(result);
        } else {
            return Result.error("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 发送登录验证码
     */
    @PostMapping("/send/login")
    @Operation(summary = "发送登录验证码", description = "向指定手机号发送登录验证码")
    public Result<Map<String, Object>> sendLoginCode(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            HttpServletRequest request) {
        
        String clientIp = getClientIp(request);
        log.info("发送登录验证码请求，手机号：{}，IP：{}", phoneNumber, clientIp);
        
        boolean success = smsService.sendLoginCode(phoneNumber);
        
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "验证码发送成功");
            result.put("expireTime", 5 * 60);
            result.put("remainingTime", smsServiceImpl.getSendLimitTime(phoneNumber));
            
            return Result.success(result);
        } else {
            return Result.error("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 发送重置密码验证码
     */
    @PostMapping("/send/reset-password")
    @Operation(summary = "发送重置密码验证码", description = "向指定手机号发送重置密码验证码")
    public Result<Map<String, Object>> sendResetPasswordCode(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            HttpServletRequest request) {
        
        String clientIp = getClientIp(request);
        log.info("发送重置密码验证码请求，手机号：{}，IP：{}", phoneNumber, clientIp);
        
        boolean success = smsService.sendResetPasswordCode(phoneNumber);
        
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "验证码发送成功");
            result.put("expireTime", 5 * 60);
            result.put("remainingTime", smsServiceImpl.getSendLimitTime(phoneNumber));
            
            return Result.success(result);
        } else {
            return Result.error("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 验证验证码
     */
    @PostMapping("/verify")
    @Operation(summary = "验证验证码", description = "验证手机号和验证码是否匹配")
    public Result<Map<String, Object>> verifyCode(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            
            @Parameter(description = "验证码") 
            @RequestParam 
            @NotBlank(message = "验证码不能为空")
            @Pattern(regexp = "^\\d{6}$", message = "验证码格式不正确") 
            String code,
            
            @Parameter(description = "验证码类型") 
            @RequestParam 
            @NotBlank(message = "验证码类型不能为空") 
            String type,
            
            HttpServletRequest request) {
        
        String clientIp = getClientIp(request);
        log.info("验证验证码请求，手机号：{}，类型：{}，IP：{}", phoneNumber, type, clientIp);
        
        boolean success = smsService.verifyCode(phoneNumber, code, type);
        
        Map<String, Object> result = new HashMap<>();
        result.put("verified", success);
        result.put("message", success ? "验证成功" : "验证码错误或已过期");
        
        if (success) {
            return Result.success(result);
        } else {
            return Result.error("验证码错误或已过期");
        }
    }

    /**
     * 检查发送限制
     */
    @GetMapping("/check-limit")
    @Operation(summary = "检查发送限制", description = "检查指定手机号的发送限制状态")
    public Result<Map<String, Object>> checkSendLimit(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber) {
        
        boolean canSend = smsService.checkSendLimit(phoneNumber);
        long remainingTime = smsServiceImpl.getSendLimitTime(phoneNumber);
        int remainingCount = smsServiceImpl.getRemainingDailyCount(phoneNumber);
        
        Map<String, Object> result = new HashMap<>();
        result.put("canSend", canSend);
        result.put("remainingTime", remainingTime);
        result.put("remainingCount", remainingCount);
        result.put("message", canSend ? "可以发送" : "发送过于频繁，请稍后再试");
        
        return Result.success(result);
    }

    /**
     * 获取验证码状态
     */
    @GetMapping("/code-status")
    @Operation(summary = "获取验证码状态", description = "获取指定手机号和类型的验证码状态")
    public Result<Map<String, Object>> getCodeStatus(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            
            @Parameter(description = "验证码类型") 
            @RequestParam 
            @NotBlank(message = "验证码类型不能为空") 
            String type) {
        
        long expireTime = smsServiceImpl.getCodeExpireTime(phoneNumber, type);
        
        Map<String, Object> result = new HashMap<>();
        result.put("hasCode", expireTime > 0);
        result.put("expireTime", expireTime);
        result.put("message", expireTime > 0 ? "验证码有效" : "验证码不存在或已过期");
        
        return Result.success(result);
    }

    /**
     * 发送通知短信（需要管理员权限）
     */
    @PostMapping("/send/notification")
    @Operation(summary = "发送通知短信", description = "向指定手机号发送通知短信（管理员功能）")
    public Result<Void> sendNotification(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            
            @Parameter(description = "通知内容") 
            @RequestParam 
            @NotBlank(message = "通知内容不能为空") 
            String message,
            
            HttpServletRequest request) {
        
        // 这里应该检查管理员权限
        Long userId = (Long) request.getAttribute("userId");
        String clientIp = getClientIp(request);
        
        log.info("管理员{}发送通知短信，手机号：{}，内容：{}，IP：{}", userId, phoneNumber, message, clientIp);
        
        boolean success = smsService.sendNotification(phoneNumber, message);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("通知短信发送失败");
        }
    }

    /**
     * 清除验证码（管理员功能）
     */
    @DeleteMapping("/clear-code")
    @Operation(summary = "清除验证码", description = "清除指定手机号的验证码（管理员功能）")
    public Result<Void> clearCode(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            
            @Parameter(description = "验证码类型") 
            @RequestParam 
            @NotBlank(message = "验证码类型不能为空") 
            String type,
            
            HttpServletRequest request) {
        
        // 这里应该检查管理员权限
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("管理员{}清除验证码，手机号：{}，类型：{}", userId, phoneNumber, type);
        
        boolean success = smsServiceImpl.clearCode(phoneNumber, type);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("清除验证码失败");
        }
    }

    /**
     * 重置发送限制（管理员功能）
     */
    @PostMapping("/reset-limit")
    @Operation(summary = "重置发送限制", description = "重置指定手机号的发送限制（管理员功能）")
    public Result<Void> resetSendLimit(
            @Parameter(description = "手机号") 
            @RequestParam 
            @NotBlank(message = "手机号不能为空")
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
            String phoneNumber,
            
            HttpServletRequest request) {
        
        // 这里应该检查管理员权限
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("管理员{}重置发送限制，手机号：{}", userId, phoneNumber);
        
        boolean success = smsServiceImpl.resetSendLimit(phoneNumber);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("重置发送限制失败");
        }
    }

    /**
     * 获取短信发送统计（管理员功能）
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取短信发送统计", description = "获取短信发送的统计信息（管理员功能）")
    public Result<Map<String, Object>> getSmsStatistics(
            @Parameter(description = "统计日期") @RequestParam(required = false) String date,
            HttpServletRequest request) {
        
        // 这里应该检查管理员权限
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("管理员{}查询短信统计，日期：{}", userId, date);
        
        // 这里可以实现统计逻辑
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalSent", 1000);
        statistics.put("successRate", 98.5);
        statistics.put("registerCodes", 600);
        statistics.put("loginCodes", 300);
        statistics.put("resetCodes", 100);
        
        return Result.success(statistics);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}